#!/usr/bin/python
#sometimes dockable databases tail -> find last molecule in OUTDOCK file -> delete from database

import sys, string,os

in_file = open(sys.argv[1], 'r')
array_number = sys.argv[2]
job_number = int(sys.argv[3])
failed_molis = open('failed.db_' + str(job_number), 'w')

in_file_lines = in_file.readlines()

if len(in_file_lines) >= job_number-1:
	okay = True
	line = in_file_lines[job_number-1]
else:
	okay = False
	print 'nothing to do for line', job_number
in_file.close()
if okay:
	line = line.strip()
	number = line.split('_')[1]
	print number
	print "start_dock.bin.o" + array_number + "." + number
	if os.path.exists("start_dock.bin.o" + array_number + "." + number):
		bin_file = open("start_dock.bin.o" + array_number + "." + number, 'r')

		for bin_file_line in bin_file.readlines():
			if  bin_file_line.find('db_file') <> -1:
				#print bin_file_line
				zipped_file = bin_file_line.split('-> ')[1]
				zipped_file = zipped_file.strip()
				break
		bin_file.close()
		print zipped_file
		#unzip file
		command = 'bunzip2 ' + zipped_file
		print command
		os.system(command)

		
		#find stop point in OUTDOCK
		outdock_file = open('acd_' + number + '/OUTDOCK', 'r')
		outdock_file_lines = outdock_file.readlines()
		outdock_file.close()
		last_line = outdock_file_lines[len(outdock_file_lines)-1]

		if last_line[1:3] == 'Ar':
			last_line = last_line.split('le ')[1]
			last_line = last_line.strip()
		elif last_line[0:2] == 'At':
			last_line = last_line.split('y @ ')[1]
			last_line = last_line.strip()
		elif last_line[1:3] == 're':
			#read error on database (Ensemble coordinate list)
			#take moli before last line
			last_line = outdock_file_lines[len(outdock_file_lines)-2]
			last_line = last_line[6:16].strip()

		else:
			last_line = last_line[6:16].strip()
		print last_line
		last_line = last_line.replace('V', '')
		#short numbers are a problem
		if last_line.find(' ') <> -1:
			#contains still spaces and number at end
			last_line = last_line.split(' ')[0]
			last_line = last_line.strip()
			print last_line

		if last_line.isdigit():
			#this is not elgant but functional
			outdock_file = open('acd_' + number + '/OUTDOCK', 'r')
			failed_id_occ = 0
			for outdock_file_lines in outdock_file.readlines():
				if outdock_file_lines.find(last_line) <> -1 and outdock_file_lines[5].isdigit():
					failed_id_occ = failed_id_occ + 1
			outdock_file_lines = outdock_file.read()
			outdock_file.close()
			#print outdock_file_lines

			print failed_id_occ, 'failed_id_occ'
			
			
			failed_id = int(last_line)

			#delete file from db_filez
			file_name = os.path.basename(zipped_file)
			dir_name = os.path.dirname(zipped_file)
			new_file_name = file_name[0:-4]
			new_file_name = new_file_name.split('.')[0] + '_new.db'
			new_db = open(dir_name + '/' + new_file_name, 'w')
			old_db = open(zipped_file[0:-4], 'r')
		
  			print "processing file " + file_name
  			family = 'false'
  			molecule = []
  			reject = False
			found = True
			reject_id = 0
			counter = 0
 			for old_db_lines in old_db.xreadlines():
    				if family == 'true':
			           if old_db_lines[0] <> 'M':
					reject = True #this is a broken molecule
				   else:
					#print '--', old_db_lines
					#print '--', old_db_lines[47:54]
      					label = string.strip(old_db_lines[47:56])
					label = label.replace('V', '')
					#short numbers are a problem
					if label.find(' ') <> -1:
						#contains still spaces and number at end
						label = label.split(' ')[0]
						label = label.strip()
					label_id = int(label)
					#print label_id, failed_id
					if label_id == failed_id:
						print 'found label' , label_id
						found = True
						counter = counter + 1
						print counter
						if counter > failed_id_occ: #that is the case if molecules occurs y times but was only docked x times
							reject = True
							print 'delete', label_id
					elif found and counter == failed_id_occ: #the last molecule was successfully docked in all versions
						reject = True #next moli has to be rejected
						found = False
						reject_id = label_id
						print 'delete', reject_id
					elif reject_id == label_id: #if compound occurs several time in db -> all have to be deleted
						reject = True
						print 'delete here', reject_id
			

				
      				   family = 'false'
     				elif old_db_lines[0:6] =='Family':
       					family = 'true'
       					if not reject:
         					for k in molecule:
	   						new_db.write(k)
					else:
         					for k in molecule:
	   						failed_molis.write(k)

	 					reject = False
	 				molecule = []
	   
    				molecule.append(old_db_lines)
			#save last molecule:
       			if not reject:
         			for k in molecule:
	   				new_db.write(k)
			new_db.close()
			old_db.close()			

			#zip file
			command = 'bzip2 ' + dir_name + '/' +new_file_name
			print command
			os.system(command)
			#command = 'bzip2 ' + dir_name + '/' +file_name[0:-4]
			command = 'rm -f ' + dir_name + '/' +file_name[0:-4]
			print command
			os.system(command)
			

		else:
			print 'could not work with OUTDOCK file' , number

	else:
		print number, ' does not exist'

failed_molis.close()


